package com.uade.tp3.g06;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	public static final String PREFS_FILE = "PrefsFile";
	public static final String SERVICE_LOGIN = "http://ecancha.com.ar/ws.php?modulo=login&action=logon&id=";

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        SharedPreferences settings = getSharedPreferences(PREFS_FILE, 0);
        String sCelular = settings.getString("celular", "");
        
        EditText etCelular = (EditText) findViewById(R.id.etCelular);
        etCelular.setText(sCelular);
        
//        if (firstrun==true) {
//        	Intent i = new Intent(MainActivity.this, UserCreator.class);
//    		startActivity(i);
//        }

//        TextView tvNombre = (TextView)findViewById(R.id.tvNombre);
//        TextView tvApellido = (TextView)findViewById(R.id.tvApellido);
//        TextView tvCelular = (TextView)findViewById(R.id.tvCelular);
        
//        Toast.makeText(MainActivity.this, nombre + " " + apellido + " " + celular, Toast.LENGTH_LONG).show();
//        ((TextView)tvNombre).setText(nombre);
//        ((TextView)tvApellido).setText(apellido);
//        ((TextView)tvCelular).setText(celular);
//        
        
    }
    
    public void Login(View v) {
    	
    	EditText etCelular = (EditText) findViewById(R.id.etCelular);
    	String sCelular = etCelular.getText().toString();
    	
    	JsonRetriever retriever = new JsonRetriever();
    	String LogResult = retriever.getJsonFromUrl(SERVICE_LOGIN + sCelular);
    	
    	if (LogResult.equals("LogOK")) {
    		SharedPreferences settings = getSharedPreferences(PREFS_FILE, 0);
    		SharedPreferences.Editor editor = settings.edit();
    		editor.putString("celular", sCelular);
            editor.commit();
            
    		Toast.makeText(MainActivity.this, R.string.login_ok, Toast.LENGTH_LONG).show();
    		Intent i = new Intent(MainActivity.this, MatchViewer.class);
    		startActivity(i);
    	} else if (LogResult.equals("LogError")) {
    		Toast.makeText(MainActivity.this, R.string.not_found, Toast.LENGTH_LONG).show();
        	Intent i = new Intent(MainActivity.this, UserCreator.class);
    		startActivity(i);
		} else {
    		Toast.makeText(MainActivity.this, "Error desconocido. Verificar servicio web.", Toast.LENGTH_LONG).show();
    	}

    }
    
}